﻿using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using OGT.DataService.Contract;
using OGT.FileTransferClient;
using OGT.FileTransferClient.Service;
using OGT.WCF.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace QueryByServerDemo
{
    public partial class QueryForm : Form
    {
        public QueryForm()
        {
            InitializeComponent();

            _cachedData = new Dictionary<TableInfo, DataTable>();
        }

        private IDataService _dataService;

        private ITransferQueueService _fileService;

        private Dictionary<TableInfo, DataTable> _cachedData;

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            string serviceUrl = txtServer.Text.Trim();

            if (serviceUrl.Length == 0)
            {
                MessageBox.Show("服务器地址无效。");
                return;
            }

            WCFClient client = WCFClient.Create(serviceUrl);

            if (client != null)
            {
                _dataService = client.GetService<IDataService>();

                try
                {
                    if (_dataService != null)
                    {

                        List<string> tableNames = new List<string>();
                        bindingSource1.DataSource = _dataService.GetTableInfos();
                        //List<TableInfo> infos = _dataService.GetTableInfos();
                        //foreach (TableInfo info in infos)
                        //{
                        //    tableNames.Add(info.Caption + info.Name);
                        //}
                        //gcTable.DataSource = tableNames;
                        //gvTable.Columns[0].Caption = "主题";
                        gcTable.DataSource = bindingSource1;
                        gvTable.OptionsDetail.ShowDetailTabs = false;
                        gcStruct.DataBindings.Add("DataSource", bindingSource1, "Columns");

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void QueryForm_Load(object sender, EventArgs e)
        {
            this.txtServer.Text = ConfigMgr.GetServer();
        }

        //双击某个表查看表中数据
        private void gcTable_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            xtraTabControl1.SelectedTabPageIndex = 1;
            GridHitInfo hitInfo = gvTable.CalcHitInfo(new Point(e.X, e.Y));
            if (hitInfo.InRow)
            {
                string tableName = gvTable.GetRowCellValue(hitInfo.RowHandle, gvTable.Columns["Name"]).ToString();
                //GetData()
                //DataTable table = GetTable(tableName);


                //GetDataByParameters()
                //List<SqlParameterInfo> paras = CreateParas();
                //DataTable table = GetTable(tableName, paras);

                //GetTopRow()
                DataTable table = GetTable(tableName, 100);

                //getDistinctData
                //string dictinctColumn = "HZJH";
                //DataTable table = GetTable(tableName, dictinctColumn);

                gvData.Columns.Clear();
                gcData.DataSource = table;

            }
        }

        //GetData()
        private DataTable GetTable(string tableName)
        {
            string whereClause = string.Format("where DOCUMENT.Id<100");
            return _dataService.GetData(tableName, whereClause);
        }
        //GetDataByParameters()
        private DataTable GetTable(string tableName, List<SqlParameterInfo> paras)
        {
            //Oracle库支持‘@’与‘:’两种前缀。
            string whereClause = string.Format("WHERE JJCSJ.HZJH=:HZJH");
            //string whereClause = string.Format("WHERE JJCSJ.HZJH=@HZJH");
            return _dataService.GetDataByParameters(tableName, whereClause, paras);
        }

        //getTopRow()
        private DataTable GetTable(string tableName, int rowCount)
        {
            string whereClause = string.Format("");
            return _dataService.GetTopRows(tableName, 1000, whereClause);
            // _dataService.GetTopRowsByParameters();
        }

        //getDistinctData
        private DataTable GetTable(string tableName, string dictinctColumn)
        {
            string whereClause = string.Format("");
            return _dataService.GetDistinctData(tableName, dictinctColumn, whereClause);
        }

        //构造参数
        private List<SqlParameterInfo> CreateParas()
        {
            List<SqlParameterInfo> parameters = new List<SqlParameterInfo>();
            parameters.Add(new SqlParameterInfo() { ParameterName = "HZJH", ParameterValue = "疃3-斜50" });

            return parameters;
        }

        //获取文件服务地址
        private string GetFileTransferServer()
        {
            //_dataService.SetUser("");
            return _dataService.GetFileTransferServer();
        }
        //保存服务地址到app.config
        private void QueryForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            ConfigMgr.Save(txtServer.Text);
        }

        private void gvData_RowCountChanged(object sender, EventArgs e)
        {
            this.barStaticItem1.Caption = "RowCount:" + this.gvData.RowCount;
        }

        //private void btnFileServer_Click(object sender, EventArgs e)
        //{
        //    string configSavePath = @"E:\新工作\文件服务器\New\配置信息";
        //    string fileTransAddress = GetFileTransferServer();
        //    _fileService = InitializeTransferQueueService(configSavePath, "文档服务测试", fileTransAddress, 10, 0.1, new Dictionary<string, string>(), true);

        //    DownloadSelectedFiles();
        //}

        private void DownloadSelectedFiles()
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = "选择下载目录";
            fbd.ShowNewFolderButton = true;
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                _fileService.DownloadCompleted -= _fileService_DownloadCompleted;
                _fileService.DownloadCompleted += _fileService_DownloadCompleted;
                List<DocumentModel> documents = GetDocumentModels();
                for (int i = 0; i < documents.Count; i++)
                {
                    _fileService.DownloadFileAsync(null, documents[i].MD5, fbd.SelectedPath + "\\" + documents[i].Name, null);
                }
            }
        }

        void _fileService_DownloadCompleted(object sender, TransferCompletedEventArgs e)
        {
            MessageBox.Show(Path.GetFileName("“"+e.TargetFile) + "” 下载成功");
        }

        private List<DocumentModel> GetDocumentModels()
        {
            List<DocumentModel> models = new List<DocumentModel>();
            int[] allSelectedIndex = gvData.GetSelectedRows();
            for (int i = 0; i < allSelectedIndex.Length; i++)
            {
                DocumentModel model = new DocumentModel();
                model.ID = Convert.ToInt32(gvData.GetRowCellDisplayText(allSelectedIndex[i], gvData.Columns["ID"]));
                model.Name = gvData.GetRowCellDisplayText(allSelectedIndex[i], gvData.Columns["NAME"]).ToString();
                model.MD5 = gvData.GetRowCellDisplayText(allSelectedIndex[i], gvData.Columns["IDENTIFIER"]).ToString();
                models.Add(model);
            }
            return models;
        }
        /// <summary>
        /// 获取传输服务
        /// </summary>
        /// <param name="configName"> 配置名称，可以任意自定义该名称 </param>
        /// <param name="transferServiceAddress"> 传输服务地址 </param>
        /// <param name="retryTimes"> 重试次数</param>
        /// <param name="retryInterval"> 重试时间（分钟） </param>
        /// <param name="extraInfos"> 扩展信息列 </param>
        /// <param name="allowEncrypt"> 是否加密</param>
        /// <returns> 传输服务</returns>
        public ITransferQueueService InitializeTransferQueueService(string configSavePath, string configName, string transferServiceAddress, int retryTimes, double retryInterval, Dictionary<string, string> extraInfos, bool allowEncrypt)
        {
            //创建传输配置
            TransferQueueConfig tranferConfig = new TransferQueueConfig();
            tranferConfig.Address = transferServiceAddress;
            tranferConfig.AllowEncrypt = allowEncrypt;
            tranferConfig.RetryTimes = retryTimes;
            tranferConfig.RetryInterval = retryInterval;
            //如果不设置SavePath,将默认保存到当前程序目录下
            if (!Directory.Exists(configSavePath))
                Directory.CreateDirectory(configSavePath);
            tranferConfig.SavePath = configSavePath;
            //创建传输管理器      
            if (TransferQueueManager.ServiceCache.ContainsKey(configName) == false)
                TransferQueueManager.RegisterTransferConfig(configName, tranferConfig);

            //创建并初始化传输服务         
            ITransferQueueService service = TransferQueueManager.GetTransferQueueService(configName);
            service.InitializeService();
            return service;
        }

        private void tmiDownload_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvData.SelectedRowsCount == 0)
                {
                    MessageBox.Show("请选择要下载的文档");
                    return;
                }

                string configSavePath = @"E:\新工作\文件服务器\New\配置信息";
                string fileTransAddress = GetFileTransferServer();
                if (_fileService == null)
                    _fileService = InitializeTransferQueueService(configSavePath, "文档服务测试", fileTransAddress, 10, 0.1, new Dictionary<string, string>(), true);

                DownloadSelectedFiles();
            }
            catch { }
        }





    }
}
